package edu.sctu.yueding.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.mobsandgeeks.saripaar.Rule;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;

import java.util.HashMap;

import edu.sctu.yueding.R;
import edu.sctu.yueding.bean.JsonBaseBeen;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;

/**
 * Created by fll on 2016/8/3.
 */
public class SignUpAddMemberActivity extends BaseActivity implements Validator.ValidationListener {

    private ImageView mBackButton;

    @Required(order = 1, message = "必填选项！")
    private EditText mUserNameEditText;

    @Required(order = 2, message = "必填选项！")
    @TextRule(order = 3, minLength = 18, maxLength = 18, message = "请输入正确的身份证号！")
    private EditText mIDNumberEditText;

    @Required(order = 4, message = "必填选项！")
    @TextRule(order = 5, minLength = 11, maxLength = 11, message = "请输入正确的电话号码！")
    private EditText mPhoneNumberEditText;

    private TextView mGenderEditText;
    private ProgressDialog progressDialog;
    private ProgressUtil progressUtil;
    private SelectSexPopupWindow selectSexPopupWindow;
    private Activity mActivity;

    private TextView submitTxt;

    private String name, gender, idNumber, phoneNumber, token;
    private int teamId;
    private long routeId;
    private SharePreference sharePreference;

    private Validator validator;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_up_add_member);
        initView();
        initSystemBar(this, R.color.hometext);
    }

    private void initView() {
        mActivity = this;
        validator = new Validator(this);
        validator.setValidationListener(this);
        mBackButton = (ImageView) findViewById(R.id.sign_up_add_member_back_button);

        mUserNameEditText = (EditText) findViewById(R.id.sign_up_add_member_edittext_name);
        mGenderEditText = (TextView) findViewById(R.id.sign_up_add_member_edittext_sex);
        mIDNumberEditText = (EditText) findViewById(R.id.sign_up_add_member_edittext_id);
        mPhoneNumberEditText = (EditText) findViewById(R.id.sign_up_add_member_edittext_phone);
        submitTxt = (TextView) findViewById(R.id.sign_up_add_member_add_button);

        mBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                removeCache();
                finish();
            }
        });

        submitTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                validator.validate();

            }
        });

        sharePreference = SharePreference.getInstance(this);
        teamId = sharePreference.getInt(CacheConfig.CACHE_SELECTED_TEAM_ID);
        token = sharePreference.getString(CacheConfig.CACHE_TOKEN);

        mGenderEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean isOpen = imm.isActive();//isOpen若返回true，则表示输入法打开
                if (isOpen) {
                    /**
                     * 隐藏软键盘
                     */
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            SignUpAddMemberActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
                initPopupWindow();
            }
        });

    }


    /**
     * 初始化PopupWindow
     */
    private void initPopupWindow() {
        View view = LayoutInflater.from(mActivity).inflate(R.layout.select_sex, null);
        LinearLayout boyBtn, girlBtn;
        Button cancelBtn;
        lightOff();
        selectSexPopupWindow = new SelectSexPopupWindow(mActivity,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                view);

        selectSexPopupWindow.setAnimationStyle(R.style.select_sex_popupwindow_anim);
//        selectSexPopupWindow.showAsDropDown(mGenderEditText, 0, 0);
        selectSexPopupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);//设置从底部弹出

        boyBtn = (LinearLayout) view.findViewById(R.id.id_select_sex_boy);
        girlBtn = (LinearLayout) view.findViewById(R.id.id_select_sex_girl);
        cancelBtn = (Button) view.findViewById(R.id.id_select_sex_cancel);

        selectSexPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();
            }
        });

        boyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGenderEditText.setText("男");
                selectSexPopupWindow.dismiss();
            }
        });

        girlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGenderEditText.setText("女");
                selectSexPopupWindow.dismiss();
            }
        });

        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectSexPopupWindow.dismiss();
            }
        });
    }

    /**
     * 内容区域变亮
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 1.0f;
        mActivity.getWindow().setAttributes(lp);
    }

    /**
     * 内容区域变暗
     */
    private void lightOff() {
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = .3f;
        mActivity.getWindow().setAttributes(lp);
    }


    /**
     * 点解添加成员
     *
     * @param
     */
    public void add() {

        progressUtil = ProgressUtil.getInstance(SignUpAddMemberActivity.this, "");

        Log.e("enroll token", token);
        if (isRightInfo() != null) {

            progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, false);

            String token = sharePreference.getString(CacheConfig.CACHE_TOKEN);

            teamId = sharePreference.getInt(CacheConfig.CACHE_TEAM_ID);
            Log.e("teamId",teamId+"");
            GetVolleyHttp.getInstance(this).getStringPOSTJsonData(URLConfig.URL_ADD_TEAM_MEMBERS + teamId + "/members",
                    isRightInfo(), new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {

                            Log.e("ffff", response);
                            JsonBaseBeen jsonBaseBeen = JSON.parseObject(response, new TypeReference<JsonBaseBeen>() {
                            }.getType());
                            if (jsonBaseBeen.getMeta().getCode() == 200) {
                                Toast.makeText(SignUpAddMemberActivity.this, "添加成功" + name, Toast.LENGTH_SHORT).show();
//                                setMemberInfoCache();
                                finish();
                            }else if (jsonBaseBeen.getMeta().getCode() == 40000701) {
                                Toast.makeText(SignUpAddMemberActivity.this, "团队人数超出限制", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(SignUpAddMemberActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                            }
                            progressUtil.dismiss(progressDialog);

                        }

                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
//                            removeCache();
                            progressUtil.dismiss(progressDialog);
                            Toast.makeText(SignUpAddMemberActivity.this, "添加失败，请稍后重试！", Toast.LENGTH_SHORT).show();
                        }
                    }, URLConfig.BEAREAR + token);

        } else {
            progressUtil.dismiss(progressDialog);

        }
    }

    /**
     * 判断成员信息是否正确
     *
     * @return
     */
    private HashMap<String, String> isRightInfo() {
        final HashMap<String, String> map = new HashMap<>();

        name = mUserNameEditText.getText().toString();
        gender = mGenderEditText.getText().toString();
        idNumber = mIDNumberEditText.getText().toString();
        phoneNumber = mPhoneNumberEditText.getText().toString();
        routeId = sharePreference.getLong(CacheConfig.CACHE_ROUTE_ID);

        String matchId = sharePreference.getString(CacheConfig.CACHE_MATCH_ID);
        Log.e("matchId", matchId);

        map.put("realName", name);
        map.put("gender", gender);
        map.put("phoneNumber", phoneNumber);
        map.put("idNumber", idNumber);
        map.put("routeId", routeId + "");
        map.put("matchId", matchId);
        return map;

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
//            removeCache();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    private void setMemberInfoCache() {
//        sharePreference = SharePreference.getInstance(this);
//        sharePreference.setCache(CacheConfig.CACHE_ADD_MEMBER_REAL_NAME, name);
//        sharePreference.setCache(CacheConfig.CACHE_ADD_MEMBER_ID_CARD, idNumber);
//        sharePreference.setCache(CacheConfig.CACHE_ADD_MEMBER_PHONE, phoneNumber);
//        sharePreference.setCache(CacheConfig.CACHE_ADD_MEMBER_SEX, gender);
//    }
//
//    private void removeCache() {
//        sharePreference = SharePreference.getInstance(this);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_REAL_NAME);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_PHONE);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_SEX);
//        sharePreference.removeOneCache(CacheConfig.CACHE_ADD_MEMBER_ID_CARD);
//    }

    @Override
    public void onValidationSucceeded() {

        add();
    }

    @Override
    public void onValidationFailed(View failedView, Rule<?> failedRule) {

        String message = failedRule.getFailureMessage();

        if (failedView instanceof EditText) {
            failedView.requestFocus();
            ((EditText) failedView).setError(message);
        } else {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }

    }


}
